package com.wangyf.thread.c_016_phaser;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * bulkRegister 估量注册数量
 * arriveAndAwaitAdvance 注册
 * arriveAndDeregister 减少注册数量
 * register 增加注册数量
 * 类似有层级的CyclicBarrier 先是7个人到场  7个人吃 7个人离开 取消注册 5个人 仅剩新郎新娘进入洞房/拥抱
 * Created by feng on 2021/1/4.
 */
public class PhaserTest {
    static Random random = new Random();
    static MarriagePhaser phaser = new MarriagePhaser();

    static void milliSleep(int n) {
        try {
            TimeUnit.MILLISECONDS.sleep(n);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        phaser.bulkRegister(7);
        for (int i = 0; i < 5; i++) {
            new Thread(new Person("person"+ i)).start();

        }
        new Thread(new Person("新郎")).start();
        new Thread(new Person("新娘")).start();
    }

    static class MarriagePhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0:
                    System.out.println("所有人到齐了！");
                    return false;
                case 1:
                    System.out.println("所有人吃完了！");
                    return false;
                case 2:
                    System.out.println("所有人离开了！");
                    System.out.println("婚礼结束！");
                    return true;
                default:
                    return true;
            }

        }
    }
    static class Person implements Runnable {
        String name;

        public Person(String name) {this.name = name;}

        public void arrive() {
            milliSleep(random.nextInt(1000));
            System.out.printf("%s 到达现场！\n", name);
            phaser.arriveAndAwaitAdvance();
        }
        public void eat() {
            milliSleep(random.nextInt(1000));
            System.out.printf("%s 吃完！\n", name);
            phaser.arriveAndAwaitAdvance();
        }
        public void leave() {
            milliSleep(random.nextInt(1000));
            System.out.printf("%s 离开！\n", name);
            phaser.arriveAndAwaitAdvance();
        }
        public void hug() {
            if ("新郎".equals(name) || "新娘".equals(name)) {
                milliSleep(random.nextInt(1000));
                System.out.printf("%s 洞房！\n", name);
                phaser.arriveAndAwaitAdvance();
            } else {
                // 取消注册
                phaser.arriveAndDeregister();
                // 增加注册数量
                //phaser.register();
            }
        }

        @Override
        public void run() {
            arrive();
            eat();
            leave();
            hug();
        }
    }
}
